<template>
	<view class="container">

		<!-- 顶部栏 -->

		<!-- <view class="nav-bar">
			<navigator open-type="navigateBack" class="back-btn">
				<image src="https://yun.qiongtuyule.com/static/arrow_left.png" class="icon_left" />
			</navigator>
			<text class="title">设备维护</text>

		</view> -->

		<!-- 设备信息卡片 -->
		<view class="card">
			<view class="card-title">
				<text>{{ projectName }} / {{ regionName }}</text>
				<text class="status abnormal">异常</text>
			</view>
			<view class="info">电量：{{ battery }}　信号强度：{{ signal }}</view>
			<view class="info">设备编号：{{ deviceCode }}</view>
			<!-- <view class="info">更新时间：{{ updateTime }}</view> -->
		</view>

		<!-- 检修表单 -->
		<view class="form">
			<text class="form-title">维护措施</text>

			<!-- 检修项 -->
			<view v-for="(item, index) in checkItems" :key="index" class="check-row">
				<view style="display:flex;">
					<view class="dz-jcx-no">{{index+1}}</view> {{item.label}}
				</view>
				<radio-group @change="e => item.status = e.detail.value">
					<label style="margin-right:10px;font-size:14px;">
						<radio value="normal" :checked="item.status==='normal'" /> 正常
					</label>
					<label style="font-size:14px;">
						<radio value="abnormal" :checked="item.status==='abnormal'" /> 异常
					</label>
				</radio-group>
			</view>

			<!-- 备注 -->
			<input class="input" placeholder="请输入备注信息（选填）" v-model="remark" />

			<!-- 图片上传 -->
			<view>
				<fileUploader limitsize="10240" @get-img="getImg" v-if="canEdit"></fileUploader>
				<!-- 				<view v-else class="dz-from-fj-edit" v-for="(item,index) in imgArr" :key="index">
					<image :src="item" class="dz-from-fj-img-img"></image>
				</view> -->
				<!-- <image v-if="imagePath" :src="imagePath" class="preview-img" /> -->
				<!-- <view v-else class="upload-placeholder">＋ 上传图片</view> -->
			</view>

			<!-- 检修结果 -->
			<view class="check-result">
				<text class="check-label">检修结果</text>
				<radio-group @change="e => finalStatus = e.detail.value">
					<label>
						<radio value="normal" :checked="finalStatus==='normal'" /> 启动
					</label>
					<label>
						<radio value="abnormal" :checked="finalStatus==='abnormal'" /> 异常
					</label>
				</radio-group>
			</view>
		</view>

		<!-- 提交按钮 -->
		<button class="submit-btn" @tap="subscribeMsg">启动设备</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				canEdit: true,
				imgArr: [],
				projectName: '',
				regionName: '',
				battery: '',
				signal: '',
				deviceCode: '',
				updateTime: '',
				checkItems: [
					// {
					// 	label: '监测绳',
					// 	status: ''
					// },
					// {
					// 	label: '设备电池',
					// 	status: ''
					// }
				],
				remark: '',
				finalStatus: 'normal'
			};
		},
		onLoad(opts) {
			if (opts && opts.id) {
				this.deviceId = opts.id;
				this.fetchDeviceData();
			}
		},
		methods: {
			subscribeMsg() {
				// 模板 ID 数组
				const tmplIds = ['j15yj3pp6BVvT6oegd97XAMlFbHwtk1CmE6zL_IwEUA'];

				wx.requestSubscribeMessage({
					tmplIds: tmplIds,
					success: (res) => {
						console.log('用户订阅结果:', res);
						if (res[tmplIds[0]] === 'accept') {
							// 调用后端接口，让后端去发送消息
							uni.login({
								provider: 'weixin',
								success: (loginRes) => {

									this.sendSubscribe(loginRes.code, tmplIds);


								}
							});
						}
					}
				});
			},
			async sendSubscribe(code, tmplIds) {
				let res = await this.$lib.$http.post({
					url: this.$lib.$urlMap.sendSubscribeMsg,
					data: {
						code: code,
						templateId: tmplIds[0]
					},
					needLogin: true
				})
				if (res.code == 1) {
					// console.log(res.data)
					// uni.showModal({
					// 	title: "订阅成功"
					// })


				}

				this.submitForm()
			},
			submitForm() {
				// 简单校验
				// const incomplete = this.checkItems.some(i => !i.status) || !this.finalStatus;
				// if (incomplete) {
				// 	return uni.showToast({
				// 		title: '请完整填写表单',
				// 		icon: 'none'
				// 	});
				// }

				// 提交逻辑（可替换为后端接口）
				// console.log('提交内容：', {
				// 	checkItems: this.checkItems,
				// 	remark: this.remark,
				// 	image: this.imagePath,
				// 	finalStatus: this.finalStatus
				// });

				// uni.showToast({
				// 	title: '提交成功',
				// 	icon: 'success'
				// });
				const payload = {
					device_id: this.deviceId,
					check_items: this.checkItems,
					remark: this.remark,
					final_status: this.finalStatus,
					image_url: this.imgArr.join(',') // 如果你后端支持 base64 或临时路径，直接传；否则需先上传
				};

				this.$lib.$http.post({
					url: this.$lib.$urlMap.submitMaintainForm, // 替换为你的实际接口路径
					data: payload,
					needLogin: true
				}).then(res => {
					if (res.code === 1) {
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						});
						// 可选：跳转或返回
						setTimeout(() => uni.navigateBack(), 1000);
					} else {
						uni.showToast({
							title: res.msg || '提交失败',
							icon: 'none'
						});
					}
				}).catch(() => {
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				});
			},
			async fetchDeviceData() {
				const res = await this.$lib.$http.post({
					url: this.$lib.$urlMap.abnormalListDetail,
					data: {
						device_id: this.deviceId
					},
					needLogin: true
				});
				if (res.code === 1 && res.data) {
					const d = res.data;
					this.projectName = d.project_name;
					this.regionName = `${d.area_name2 || ''}${d.area_name1 || ''}`;
					this.battery = d.battery != null ? d.battery + '%' : '';
					this.signal = d.signal_strength != null ? d.signal_strength + '%' : '';
					this.deviceCode = d.code || '';
					this.updateTime = d.checktime;

					// 假设checkItems来自接口，初始化时赋值状态
					if (Array.isArray(d.check_items)) {
						this.checkItems = d.check_items.map(item => ({
							label: item.label,
							status: 'normal',
							id: item.itemID
						}));
					}

				} else {
					uni.showToast({
						title: '获取设备信息失败',
						icon: 'none'
					});
				}
			},
			getImg(data) {
				this.imgArr = data
			},
		}
	};
</script>

<style scoped>
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding: 30rpx;
	}

	.dz-jcx-no {
		background: #4d72ff;
		color: #fff;
		font-size: 12px;
		width: 18px;
		height: 18px;
		border-radius: 2px;
		text-align: center;
		line-height: 18px;
		margin-right: 6px;
	}


	.nav-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 30rpx;
	}

	.back-btn {
		font-size: 40rpx;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
		flex: 1;
		text-align: center;
		margin-left: -40rpx;
		/* 为了让返回按钮不挤压标题居中 */
	}

	.icons {
		display: flex;
	}

	.icon {
		width: 40rpx;
		height: 40rpx;
		margin-left: 20rpx;
	}

	.icon_left {
		width: 49rpx;
		height: 38rpx;
	}

	.header {
		text-align: center;
		font-size: 36rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.card {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.card-title {
		display: flex;
		justify-content: space-between;
		font-size: 30rpx;
		font-weight: 600;
	}

	.status.abnormal {
		color: #ff2e2e;
	}

	.info {
		margin-top: 10rpx;
		font-size: 26rpx;
		color: #666;
	}

	.form {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 20rpx;
	}

	.form-title {
		font-size: 30rpx;
		font-weight: bold;
		/* padding-bottom: 30rpx; */
	}

	.check-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 20rpx auto;
	}

	.check-label {
		font-size: 26rpx;
	}

	.input {
		background: #f7f7f7;
		border-radius: 10rpx;
		padding: 20rpx;
		font-size: 26rpx;
		margin-bottom: 30rpx;
	}

	.upload-box {
		width: 200rpx;
		height: 200rpx;
		border: 2rpx dashed #ccc;
		border-radius: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 30rpx;
	}

	.upload-placeholder {
		font-size: 24rpx;
		color: #888;
	}

	.preview-img {
		width: 100%;
		height: 100%;
		object-fit: cover;
		border-radius: 10rpx;
	}

	.check-result {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 50rpx;
	}

	.submit-btn {
		background: #1677ff;
		color: #fff;
		font-size: 30rpx;
		border-radius: 50rpx;
		height: 90rpx;
		line-height: 90rpx;
	}

	.dz-from-fj-edit .iconfont {
		font-size: 24px;
		margin-bottom: 1px
	}

	.dz-from-fj-img-img {
		width: 80px;
		height: 80px;
	}

	.dz-from-jian {
		position: absolute;
		right: 2px;
		top: 2px;
	}

	.dz-from-jian .iconfont {
		color: rgb(255, 255, 255);
		font-size: 11px;
		transform: rotate(45deg);
		border-radius: 50%;
		padding: 3px;
		background: rgb(68, 138, 255);
	}
</style>